package com.cheval.rpcframe.register;

import com.cheval.rpcframe.common.Config;

import java.io.File;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

public class LocalRegister {

    private static Map<String, Class<?>> registerInfo = new HashMap<>();

    public static void serverRegister(ClassLoader loader) {
        String serverPaths = Config.getServerPath();
        if (serverPaths == null || serverPaths.trim().equals("")) {
            return;
        }
        String[] serverPathArr = serverPaths.split(",");
        if (serverPathArr.length == 0) {
            return;
        }
        String packageName = null;
        for (String serverPath : serverPathArr) {
            packageName = serverPath;
            serverPath = serverPath.replaceAll("\\.", "/");
            URL resource = loader.getResource(serverPath);
            String f = resource.getFile();
            if(f == null || f.trim().equals("")) {
                continue;
            }
            File dir = new File(f);
            if (!dir.isDirectory()) {
                continue;
            }
            scan(dir, packageName);
        }
    }

    private static void scan(File directory, String packageName) {
        File[] files = directory.listFiles();
        if (files == null) {
            return;
        }
        String filename = null;
        String key = null;
        String temp = packageName;
        for (File file : files) {
            if (file.isDirectory()) {
                filename = file.getName();
                temp = packageName + "." + filename;
                scan(file, temp);
            } else {
                try {
                    filename = file.getName();
                    filename = filename.substring(0, filename.lastIndexOf("."));
                    temp = packageName + "." + filename;
                    Class<?> aClass = Class.forName(temp);
                    Provide provide = aClass.getAnnotation(Provide.class);
                    if (provide == null) {
                        continue;
                    }
                    key = provide.interfaceName() + provide.version();
                    registerInfo.put(key, aClass);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static Class<?> get(String interfaceName, String version) {
        if (version == null || "".equals(version.trim())) {
            interfaceName = interfaceName + "1.0";
        } else {
            interfaceName = interfaceName + version;
        }
        return registerInfo.get(interfaceName);
    }
}
